// components/choose-modal/index.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
const {
  subjectList,
  citySubjectList,
  addScore,
  schoolAdd,
  getScore
} = require('../../api/api')
const {checkLogin}=require('../../utils/util')

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isshow: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      value: 'default'
    },
    initData: {
      type: Object,
      value: {}
    },
    showYear: {
      type: Boolean,
      default: true
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    list1: [],
    checkedList: [],
    mainSubject: '',
    chooseList: [],
    score: 0,
    ranking: 0,
    currentRegion: {},
    subList: [],
    length: 3,
    cityList: [],
    cityIndex: 0,
    yearIndex: 0,
    yearList: [],
    yearDisabled: false
  },
  lifetimes: {
    attached: function () {
      var d = new Date();
      var year = d.getFullYear()
      var len = year + 3
      let yearList = []
      for (var i = year; i < len; i++) {
        yearList.push(i)
      }
      this.setData({
        yearList
      })
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  observers: {
    'isshow': function (selectIndex) {
      // 在 rate被设置时，执行这个函数
      if (this.data.isshow == true) {
        console.log('isShow')
        this.init()
        this.setData({
          yearDisabled: wx.getStorageSync('yearDisabled') || false
        })
      }
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      const provinceId = wx.getStorageSync('userCitys').code
      const year = wx.getStorageSync('year')
      const {
        yearList
      } = this.data
      const subjectInfo = wx.getStorageSync('subjectInfo')
      this.setData({
        chooseList: wx.getStorageSync('chooseList') || [],
        checkedList: wx.getStorageSync('ids') || [],
        mainSubject: wx.getStorageSync('mainSubject') || '',
        score: wx.getStorageSync('score'),
        ranking: wx.getStorageSync('ranking'),
        yearIndex: yearList.indexOf(year) > -1 ? yearList.indexOf(year) : 0,
        disabled: subjectInfo ? true : false
      })
      this.fetchCityList(provinceId)
    },
    bindPickerChange(e) {
      const {
        cityList
      } = this.data
      const index = parseInt(e.detail.value)
      const currentRegion = {
        province: cityList[index].title,
        provinceId: cityList[index].id
      }
      this.setData({
        currentRegion,
        cityIndex: index,
        checkedList: [],
        chooseList: [],
        mainSubject: '',
        subList: [],
        list1: [],
        score: '',
        ranking: ''
      })
      const provinceId = cityList[index].id
      this.getCitySubject(provinceId)
      getApp().getVoluntaryConfigCity(provinceId)
    },
    bindPickerYearChange(e) {
      this.setData({
        yearIndex: parseInt(e.detail.value)
      })
    },

    async fetchCityList(provinceId) {
      const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
      let cityIndex = 0
      if (provinceId) {
        cityList.map((item, index) => {
          if (item.id == provinceId) {
            cityIndex = index
            this.setData({
              currentRegion: {
                province: item.title,
                provinceId: item.id
              }
            })
          }
        })
      } else {
        this.setData({
          currentRegion: {
            province: cityList[cityIndex].title,
            provinceId: cityList[cityIndex].id
          }
        })
      }

      this.setData({
        cityList,
        cityIndex,
      })
      this.getCitySubject()
    },
    async getCitySubject() {
      const {
        checkedList,
        currentRegion
      } = this.data
      const {
        result
      } = await citySubjectList(currentRegion.provinceId)
      const mainList = result.filter(function (item, index, arr0) {
        return item.isPreferred > 0
      })
      const subjectList = result.filter(function (item, index, arr0) {
        return item.isPreferred == 0
      })
      const ids = wx.getStorageSync('ids')
      const list = result.filter((item) => {
        return ids.indexOf(item.subjectsId) > -1
      })
      list.map((item, index) => {
        if (item.subjectsId == this.data.mainSubject) {
          list.unshift(list.splice(index, 1)[0])
        }
      })
      this.setData({
        list1: mainList,
        chooseList: list
      })
      const {
        mode
      } = this.data
      if (checkedList.length > 0) {

        subjectList.map((item) => {
          item['choose'] = ids.indexOf(item.subjectsId) > -1
        })

      } else {
        subjectList.map((item) => {
          item['choose'] = false
        })
      }
      //  else if (mode == 'users') {
      //   const {
      //     firstSelect,
      //     secondSelect
      //   } = this.data
      //   const checkedList = []
      //   const chooseList = []
      //   if (firstSelect && firstSelect !== '') {
      //     const mainSubjectList = mainList.filter((item) => {
      //       return item.subjectsName == firstSelect
      //     })
      //     this.setData({
      //       mainSubject: mainSubjectList[0].subjectsId
      //     })
      //     checkedList.push(mainSubjectList[0].subjectsId)
      //     chooseList.push(mainSubjectList[0])
      //   }
      //   const secondSelectArray = secondSelect ? secondSelect.split(',') : []
      //   subjectList.map((item) => {
      //     if (secondSelectArray.indexOf(item.subjectsName) > -1) {
      //       checkedList.push(item.subjectsId)
      //       chooseList.push(item)
      //       item['choose'] = true
      //     }
      //   })
      //   this.setData({
      //     chooseList,
      //     checkedList
      //   })
      // }
      this.setData({
        subList: subjectList,
        length: mainList.length > 0 ? 2 : 3
      })
    },
    hide() {
      const {
        subList
      } = this.data
      subList.map((item) => {
        item.choose = false
      })
      this.setData({
        isshow: false,
        checkedList: [],
        chooseList: [],
        subList
      })
    },
    validateModal() {
      const {
        score,
        chooseList,
        ranking,
        checkedList
      } = this.data
      return new Promise((resolve, reject) => {
        if (score !== '' && chooseList.length == 3) {
          resolve()
        } else {
          if (score == '') {
            wx.showToast({
              title: '请输入分数',
              icon: 'none'
            })
          }
          console.log(chooseList)
          if (chooseList.length < 3) {
            wx.showToast({
              title: '请选择科目',
              icon: 'none'
            })
          }
        }
      })

    },
    chooseMain(e) {
      const {
        list1,
        chooseList,
        checkedList
      } = this.data
      const {
        id,
        name
      } = e.currentTarget.dataset
      if (checkedList.indexOf(id) > -1) return
      const deleteIds = list1.filter((item) => {
        return item.subjectsId !== id
      })
      const mainSubjectList = list1.filter((item) => {
        return item.subjectsId == id
      })
      const subjectsId = deleteIds[0].subjectsId
      chooseList.map((item, index) => {
        if (item.subjectsId == subjectsId) {
          chooseList.splice(index, 1)
        }
      })
      const newList = mainSubjectList.concat(chooseList)
      const newCheckedList = newList.map((item) => {
        return item.subjectsId
      })
      this.setData({
        mainSubject: id,
        firstSelect: name,
        chooseList: newList,
        checkedList: newCheckedList,
      })
      this.getRank()
    },
    chooseSubject(e) {
      const {
        id,
        choose,
        index,
        name
      } = e.currentTarget.dataset
      var {
        subList, //学科列表
        checkedList, //已选科目id
        chooseList, //已选科目
        length,
        mainSubject,
        list1
      } = this.data
      const hookSubjectList = chooseList.filter((item) => {
        return item.subjectsId !== mainSubject
      })
      const mainSubjectList = list1.filter((item) => {
        return item.subjectsId == mainSubject
      })
      const hookIds = hookSubjectList.map((item) => {
        return item.subjectsId
      })

      const mainIds = mainSubjectList.length > 0 ? mainSubjectList.map((item) => {
        return item.subjectsId
      }) : []
      subList[index].choose = !choose
      if (choose) {
        //删除
        const index = hookIds.indexOf(id)
        hookIds.splice(index, 1)
        hookSubjectList.splice(index, 1)
      } else {
        if (hookIds.length >= length) {
          subList.map((item) => {
            if (item.subjectsId == hookIds[0]) {
              item.choose = false
            }
          })
          hookIds.splice(0, 1, id)
          hookSubjectList.splice(0, 1, subList[index])

        } else {
          hookIds.push(id)
          hookSubjectList.push(subList[index])
        }
      }
      chooseList = mainSubjectList.concat(hookSubjectList.sort((a, b) => {
        return a.id - b.id
      }))
      checkedList = mainIds.concat(hookIds)
      const secondSelectArray = hookSubjectList.map((item) => {
        return item.subjectsName
      })
      this.setData({
        subList,
        checkedList,
        chooseList,
        secondSelect: secondSelectArray.join(',')
      })
      this.getRank()

    },
    async getRank() {
      const {
        score,
        currentRegion,
        mainSubject,
        chooseList,
      } = this.data
      var d = new Date();
      var year = d.getFullYear()
      var currentYear = year - 1
      if (score.length < 3 || chooseList.length < 3) return
      const ranking = await getApp().getRank(score,
        currentRegion.provinceId,
        currentYear,
        mainSubject,
        chooseList)
      this.setData({
        ranking
      })
    },
    cancel(){
      this.setData({
        isshow:false
      })
    },
    confirm(e) {
      checkLogin().then((res) => {
        var _this = this
        this.validateModal().then(async function (res) {
          const {
            mainSubject,
            chooseList,
            score,
            ranking,
            currentRegion,
            yearList,
            yearIndex
          } = _this.data
          const secondSelectList = chooseList.filter((item) => {
            return item.subjectsId !== mainSubject
          })
          const secondSelectIds = secondSelectList.map((item) => {
            return item.subjectsId
          })
          const params = {
            score,
            ranking,
            firstSelect: mainSubject,
            secondSelect: secondSelectIds.toString(),
            provinceId: currentRegion.provinceId,
            province: currentRegion.province,
            year: yearList[yearIndex]
          }
          const {
            result
          } = await addScore(params)
          wx.setStorageSync('yearDisabled', true)
          wx.setStorageSync('chooseList', chooseList)
          _this.hide()
          _this.getScore()
        })
      }).catch((e) => {
        wx.navigateTo({url:'/pages/login/index'})
      })
    },

    async getScore() {
      var {
        result
      } = await getScore()
      const subjectList = wx.getStorageSync('subjectList') || await getApp().getSubjectList()
      const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
      const currentCityList = cityList.filter((item) => {
        return item.id == result.provinceId
      })
      let newTime = Math.round(new Date())
      const userCitys = {
        code: currentCityList[0].id,
        name: currentCityList[0].title,
        time: newTime
      }
      let checkedIds = []
      const secondSelect = result.secondSelect == '' ? [] : result.secondSelect.split(',')
      var firstSelectSubjects = ''
      var secondSelectSubjects = []
      subjectList.map((item) => {
        if (result.firstSelect !== '' && item.id == result.firstSelect) {
          firstSelectSubjects = item.name
          checkedIds.push(parseInt(result.firstSelect))
        }
        if (secondSelect.indexOf(item.id) > -1 || secondSelect.indexOf(item.id.toString()) > -1) {
          secondSelectSubjects.push(item.name)
          checkedIds.push(parseInt(item.id))
        }
      })
      result.firstSelectSubjects = firstSelectSubjects
      result.secondSelectSubjects = secondSelectSubjects.join(',')
      if (checkedIds.length > 0) {
        wx.setStorageSync('ids', checkedIds)
      }
      wx.setStorageSync('mainSubject', result.firstSelect == '' ? '' : parseInt(result.firstSelect))
      wx.setStorageSync('score', result.score)
      wx.setStorageSync('ranking', result.ranking)
      wx.setStorageSync('year', result.year)
      wx.setStorageSync('userCitys', userCitys)
      wx.setStorageSync('subjectInfo', result)
      this.triggerEvent('confirm')
    },
    inputChange(e) {
      const {
        type
      } = e.currentTarget.dataset
      this.setData({
        [type]: e.detail.value
      })
      if (type == 'score' && e.detail.value.length == 3) {
        if (e.detail.value < 100 || e.detail.value > 750) {
          wx.showToast({
            title: '请输入100-750区间的整数',
            icon: 'none'
          })
          this.setData({
            ranking: ''
          })
          return
        }
        this.getRank()
      }
    },
  }
})
